import 'package:base_lib/router/page_builder.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:flutter/cupertino.dart';
import 'core/common.dart';
import 'core/router.dart';
import 'notfound/page.dart';

class Routers {
  static WRouter router = WRouter();

  static String login_page = "";

  static String main_page = "";

  static Map<String, PageBuilder> _routers = {};

  static Function determineWhetherToLoginAgain;

  ///是否需要重新登录的逻辑
  static setDetermineWhetherToLoginAgain(Function handler) {
    determineWhetherToLoginAgain = handler;
  }

  static void init(List<PageBuilder> pages) {
    router.notFoundHandler = Handler(handlerFunc:
        (BuildContext context, String path, Map<String, List<Object>> params) {
      return NotFoundPage(path, params);
    }); //空页面
    pages.forEach((page) {
      var handler = page.handler();
      router.define(page.path, handler: handler);
      _routers[page.path] = page;
    });
  }

  static void initLoginPage(String loginPage) {
    Routers.login_page = loginPage;
  }


  static void initMainPage(String mainPage) {
    Routers.main_page = mainPage;
  }

  static Future navigateTo(BuildContext context, String page,
      {Parameters parameters,
        bool forceLogin = false,
        bool replace = false,
        bool clearStack = false,
        TransitionType transition = TransitionType.nativeModal,
        Duration transitionDuration = const Duration(milliseconds: 100),
        RouteTransitionsBuilder transitionBuilder}) {
    var pageBuilder = _routers[page];
    if (pageBuilder != null) {
      pageBuilder.parameters = parameters ?? Parameters();
    }

    var path = page;
    if (forceLogin && (determineWhetherToLoginAgain.call() == true))
      path = login_page;
    return router.navigateTo(context, path,
        replace: replace,
        clearStack: clearStack,
        transition: transition,
        transitionDuration: transitionDuration,
        transitionBuilder: transitionBuilder);
  }

  static pop<T extends Object>(BuildContext context, [ T result ]) {
    router.pop(context, result);
  }

  static popUntil(BuildContext context, String path) =>
      router.popUntil(context, path);

  static popAndPushNamed(BuildContext context, String path) =>
      router.popAndPushNamed(context, path);

//  /// 生成对应的page
//  static Widget generatePage(BuildContext context, String path,
//      {Parameters parameters}) {
//    var pageBuilder = _routers[path];
//    if (pageBuilder == null) {
//      return router.notFoundHandler.handlerFunc(context, path, {});
//    }
//    pageBuilder.parameters = parameters ?? Parameters();
//    var widget = pageBuilder.handler().handlerFunc(context, path, {});
//    if (widget == null) {
//      return router.notFoundHandler.handlerFunc(context, path, {});
//    }
//    return widget;
//  }

}
